<?php
/**
 * Created by JetBrains PhpStorm.
 * User: FUHU
 * Date: 9/28/13
 * Time: 12:45 PM
 * To change this template use File | Settings | File Templates.
 */

namespace Helloworld\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

class UsersTable extends AbstractTableGateway
{
    public function __construct($adapter)
    {
        $this->table = 'users';
        $this->adapter = $adapter;

        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new UsersModel());
    }

    public function fetchAll()
    {
        return $this->select();
    }

    public function deleteUser($id)
    {
        $this->delete(array('id'=>$id));
    }

    public function getUser($id)
    {
        $rowset = $this->select(array('id'=>$id));
        if(!$row = $rowset->current()){
            throw new \Exception('Row not found');
        }
        return $row;
    }

    public function saveUser($user)
    {

        $aData = array(
            'username' => $user->username,
            'password' => $user->password,
        );

        if($user->id == null)
        {
            $this->insert($aData);
        }
        else if($user->id != 0)
        {
            $this->update($aData, array('id' => $user->id));
        }
    }
}